import { reqCode, reqLogin, reqRegister, reqUserLogout, reqUserInfo } from '@/api'

export default {
    state: {
        token: localStorage.getItem('token'),
        username: ""
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
        },
        SET_NAME(state, name) {
            // console.log(name);
            state.username = name
        },
        REMOVE_USERINFO(state) {
            state.token = ''
            state.username = ''
        }
    },
    actions: {
        async getCode({ commit }, phone) {
            let res = await reqCode(phone)
            // console.log(res);
            if (res.code == 200) {
                return res.data
            } else {
                return Promise.reject(res.message);
            }
        },
        async register({ commit }, data) {
            let res = await reqRegister(data)
            // console.log(res);
            if (res.code == 200) {
                return 'ok'
            } else {
                return Promise.reject(res.message);
            }
        },
        async login({ commit }, data) {
            let res = await reqLogin(data);
            // console.log(res.data.token);
            if (res.code == 200) {
                commit('SET_TOKEN', res.data.token)
                localStorage.setItem('token', res.data.token)
                return 'ok'
            } else {
                return Promise.reject(res.message)
            }
        },

        async getUserName({ commit }) {
            let res = await reqUserInfo();
            // console.log(res);
            if (res.code == 200) {
                commit('SET_NAME', res.data.name)
                return 'ok'
            } else {
                return Promise.reject()
            }
        },
        async logout({ commit }) {
            // console.log(222);
            let res = await reqUserLogout();
            // console.log(res,11);
            if (res.code == 200) {
                commit('REMOVE_USERINFO')
                localStorage.removeItem('token')
            } else {
                return Promise.reject()
            }


        },

    },
    getters: {}
}